
import { _decorator, Component, Node, Sprite, SpriteFrame } from 'cc';
import { BattleManager } from '../BattleManager';
import { CommandType, Message, MessageType } from '../framework/Message';
import { MessageBase } from '../framework/MessageBase';
import { MessageCenter } from '../framework/MessageCenter';
import { GameData } from '../GameData';
import { Map } from '../map/Map';
import { MiniMap } from '../map/MiniMap';
import { Utils } from '../utils/Utils';
import { Hero } from './Hero';
import { Pet } from './Pet';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = Item
 * DateTime = Sat Feb 05 2022 15:07:28 GMT+0800 (China Standard Time)
 * Author = vvc_zeng
 * FileBasename = Item.ts
 * FileBasenameNoExtension = Item
 * URL = db://assets/script/player/Item.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/zh/
 *
 */

@ccclass('Item')
export class Item extends MessageBase {
    static Instance: Item = null;

    // 存放已拥有的物品的id
    itemId: number[];
    // 藏宝图和悬赏令物品的缓存信息
    itemInfo;
    // get 仅在获得物品时生效一次 func 在战斗中持续生效 once 延迟到满足条件时生效一次 a 战前给予属性加成一次 一共 17 种物品
    itemData;
    onLoad() {
        super.onLoad()
        Item.Instance = this;
    }
    init() {
        this.messageType = MessageType.TYPE_ITEM;
    }
    initData() {
        this.itemId = [];
        this.itemInfo = {
            // 藏宝图地点
            treasurePlace: [],
            // 悬赏令指示的怪物
            monsterReward: []
        }
        this.itemData = [
            {
                a: [0, 0, 0, 0, 0, 0, 0, 30]
            },
            {
                get: () => {
                    MessageCenter.SendCustomMessage(MessageType.TYPE_HERO, CommandType.COM_HERO_HP, Math.round(Hero.Instance.abilities[0] * 0.65))
                }
            },
            {
                a: [0, 0, 0, 0, 30, 0, 0, 0]
            },
            {
                a: [0, 0, 30, 0, 0, 0, 0, 0]
            },
            {
                a: [0, 0, 0, 30, 0, 0, 0, 0]
            },
            {
                once: () => {
                    console.log("获得钥匙，可以打开宝箱");
                    // 获得钥匙时自动检索宝箱，有宝箱则打开，打开后，钥匙宝箱消失
                    if (this.itemId.indexOf(6) > -1 && this.itemId.indexOf(5) > -1) {
                        this.itemId.splice(this.itemId.indexOf(6), 1);
                        this.itemId.splice(this.itemId.indexOf(5), 1);
                        // 获得 10号物品
                        this.getItem(10);
                        console.log("获得10号物品");
                        return true;
                    } else {
                        return false;
                    }
                }
            },
            {
                get: () => {
                    console.log("获得宝箱，需要钥匙才能开箱");
                }
            },
            {
                get: () => {
                    console.log("向神灯许愿");
                    if (Pet.Instance.pet.length < 4) {
                        Pet.Instance.getPet(0)
                        console.log("神灯赐予你宠物0");
                    } else {
                        this.getItem(2);
                        console.log("神灯赐予你宝物2");
                    }
                }
            },
            {
                get: () => {
                    MessageCenter.SendCustomMessage(MessageType.TYPE_HERO, CommandType.COM_HERO_HP, Math.round(Hero.Instance.abilities[0] * 0.35))
                }
            },
            {
                // 战斗前属性临时增加一次
                a: [0, 0, 0, 0, 0, 0, 30, 0]
            },
            {
                func: () => {
                    // 战斗时持续恢复
                    if (Hero.Instance.mp < Hero.Instance.abilities[1]) {
                        MessageCenter.SendCustomMessage(MessageType.TYPE_HERO, CommandType.COM_HERO_MP, 1)
                    }
                }
            },
            {
                func: () => {
                    if (Hero.Instance.hp < Hero.Instance.abilities[0]) {
                        MessageCenter.SendCustomMessage(MessageType.TYPE_HERO, CommandType.COM_HERO_HP, 2)
                    }
                }
            },
            {
                func: (stat) => {
                    // 战斗时持续增加属性，最多加到80
                    for (let i = 4; i < stat.length; i++) {
                        if (stat[i] <= 80) {
                            stat[i] += 1;
                        }
                    }
                }
            },
            {
                buff: () => {
                    // 战斗前赋予buff
                    let _rate = Math.random()
                    let heroBuff = BattleManager.Instance.heroBuff;
                    if (_rate > 0.7) {
                        // buff
                        heroBuff.push({ id: <number>Utils.getRandomRange(0, 20), turn: 1 })
                    }
                    if (_rate < 0.3) {
                        // debuff
                        heroBuff.push({ id: <number>Utils.getRandomRange(21, 44), turn: 1 })
                    }
                }
            },
            {
                get: () => {
                    // 从21种地点中选取一个作为藏宝地点
                    let _p = <number>Utils.getRandomRange(0, 20)
                    this.itemInfo.treasurePlace.push(_p);
                    console.log("藏宝地点：", GameData.Instance.areaTips[_p][0]);
                },
                once: () => {
                    console.log(GameData.Instance.itemTips[14][0], GameData.Instance.itemTips[14][1]);
                    // 如果玩家到达了藏宝地点，获得宝物
                    let curSprite = <Sprite>(Map.Instance.node.children[Map.Instance.cur_hero_pos].getComponent("cc.Sprite"));
                    let _i = this.itemInfo.treasurePlace.indexOf(GameData.Instance.areaFrames.indexOf(curSprite.spriteFrame))
                    if (_i > -1) {
                        this.itemInfo.treasurePlace.splice(_i, 1)
                        // 获得宝物2
                        console.log("到达藏宝地点，获得宝物2");
                        this.getItem(2)
                        return true;
                    } else {
                        return false;
                    }
                }
            },
            {
                a: [0, 0, 0, 0, 0, 30, 0, 0]
            },
            {
                get: () => {
                    let _p = 2;
                    this.itemInfo.monsterReward.push(_p);
                    console.log("悬赏怪物：2号", GameData.Instance.monsterTips[_p][0]);
                },
                once: () => {
                    console.log(GameData.Instance.itemTips[16][0], GameData.Instance.itemTips[16][1]);
                    let mid = BattleManager.Instance.mid;
                    let _i = this.itemInfo.monsterReward.indexOf(mid)
                    if (_i > -1) {
                        this.itemInfo.monsterReward.splice(_i, 1)
                        this.getItem(2);
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        ]
    }
    ReveiveMessage(message: Message) {
        super.ReveiveMessage(message);
        if (message.Command == CommandType.COM_ITEM_INIT) {
            this.initData();
            console.log("初始化物品栏");
            this.node.active = true;
        }
    }
    getItem(id) {
        if (this.itemId.length < 12) {
            // 渲染新物品到提示文本层
            let n = this.node.children[this.itemId.length];
            // 点击物品时，显示物品描述信息
            n.on(Node.EventType.TOUCH_END, (e) => {
                MessageCenter.SendCustomMessage(MessageType.TYPE_MAP, CommandType.COM_MAP_SHOWTIPS, [(<Node>e.target).parent.name, (<Node>e.target).getSiblingIndex()])
            }, this);
            // 更新物品图片
            let c = <Sprite>n.getComponent("cc.Sprite");
            c.spriteFrame = GameData.Instance.itemFrames[id];

            if (typeof this.itemData[id].get == 'function') {
                this.itemData[id].get();
            }
            if (typeof this.itemData[id].once == 'function') {
                this.itemData[id].once();
            }
            this.itemId.push(id);
            console.log(this.itemId);
        } else {
            console.log("背包已满，不能再获得新物品")
        }
    }
    checkItem() {
        // 延时触发的物品只有钥匙、藏宝图、悬赏令
        // 分别在获得宝箱、到达指定类型的图块、击败指定怪物时触发
        // 并在触发后，移除

        if (MiniMap.Instance.areaMapPos == -1 && this.itemInfo.treasurePlace.indexOf(Map.Instance.cur_map[Map.Instance.cur_hero_pos][1]) != -1) {
            // 检查藏宝图
            console.log("到达藏宝图地点");

        }
        
        // 触发area事件之前 打败怪物且战斗结束之前 获得物品之时 调用这个函数，检测延时触发的物品是否满足条件
        // let ids = this.itemId.filter(v => typeof this.itemData[v].once == 'function');
        // console.log("检查延时触发物品的触发条件", ids);
        // ids.forEach(v => {
        //     if (this.itemData[v].once()) {
        //         // 如果成功触发，则移除已触发的物品
        //         console.log(this.itemId, "成功触发延迟生效的物品" + v);
        //     }
        // });
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.3/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.3/manual/zh/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.3/manual/zh/scripting/life-cycle-callbacks.html
 */
